const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require("webpack");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
// css压缩
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
// js压缩
const TerserPlugin = require("terser-webpack-plugin");
// 打包静态资源
const copyWebpackPlugin = require('copy-webpack-plugin');

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;


module.exports = {
    output: {
        path: path.resolve(__dirname, '../dist'),
        filename: 'js/[name].[chunkHash].js',
        chunkFilename: 'js/[name].[chunkHash].js',
        publicPath: './',
        // 配置拆分文件的名称
        vendor: ["vue", 'vue-router']
    },
    devtool: 'cheap-module-source-map',
    mode: 'production',
    optimization: {
        minimize: true,
        minimizer: [new TerserPlugin()], // js压缩

        splitChunks: {
            chunks: 'initial', // 只对入口文件处理
            cacheGroups: {
                vendors: {
                    test: /node_modules\//,
                    name: 'vendor',
                    priority: 10,
                    enforce: true,
                },
            }
        },
        runtimeChunk: {
            name: 'manifest'
        },
    },

    plugins: [
        new CleanWebpackPlugin(),
        // 实现持久化缓存
        new webpack.HashedModuleIdsPlugin(),
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, "../src/index.html"),
            filename: "index.html", // 输出的HTML文件名
            inject: 'body', // 将脚本注入到body中
            title: 'webpack-主页',//配置生成页面的标题
            publicPath: './'
        }),
        new MiniCssExtractPlugin({
            filename: 'css/[name].[hash].css',
            chunkFilename: 'css/[name].[hash].css',
        }),
        new OptimizeCSSAssetsPlugin(),
        new copyWebpackPlugin({
            patterns: [
                {
                    from: path.resolve(__dirname, '../src/static'),// 打包的静态资源目录地址
                    to: 'static' // 打包到dist下面的static
                }
            ]
        }),
        // 在 plugin 中添加以下代码：
        new BundleAnalyzerPlugin({
            analyzerMode: 'static',
            //  是否在默认浏览器中自动打开报告
            openAnalyzer: false,
            //  将在“服务器”模式下使用的端口启动HTTP服务器。
            analyzerPort: 9528,
            reportFilename: 'static/report.html',
        })
    ],
};
